import axios from 'axios';
import storage from './storage.js';
import axiosAdapterUniapp from 'axios-adapter-uniapp';
import env from '../envVersion.js';
// console.log('baseUrl', env.baseUrl);
const platForm = uni.getSystemInfoSync().platform;
console.log(uni.getSystemInfoSync());
const instance = axios.create({
	timeout: 60000,
	responseType: 'json',
	// baseURL: 'http://10.1.20.178:9999', // 宁天阳
	baseURL: env.baseUrl,
	adapter: axiosAdapterUniapp,
});

// 添加请求拦截器
instance.interceptors.request.use(
	(request) => {
		const accessToken = storage.token.get();
		if (accessToken && request.headers.isAuth !== false) {
			request.headers['CLIENT-TOC'] = request.headers['CLIENT-TOC'] || 'Y';
			request.headers.Authorization = request.headers.Authorization || `Bearer ${accessToken}`;
		}
		if (!request.headers) {
			request.headers = {};
		}
		// 终端类型，比如抖音、微信、h5、APP等
		request.headers.clientType = 'DOUYIN_MP';
		// 手机系统：android、ios, 处理本地联调时会为devtools，暂时处理为ios，真机下则是正常的
		request.headers.MobileType = platForm === 'devtools' ? 'ios' : platForm;

		if (env.microapp.envType === 'development' || env.microapp.envType === 'preview') {
			console.log('请求参数---->', request);
			// console.log('request.headers.clientType', request.headers.clientType);
			// console.log('request.headers.MobileType', request.headers.MobileType);
		}

		// 针对get请求去缓存处理
		if (request.method === 'get') {
			request.params = request.params || {};
			request.params.cacheTime = new Date().getTime();
		}
		return request;
	},
	(error) => Promise.reject(error)
);

// 添加响应拦截器
instance.interceptors.response.use(
	(response) => {
		if (!response.data) {
			uni.showToast({
				title: '系统异常！',
				icon: 'none',
			});
			return Promise.reject(response);
		}
		if (response.data.code === 50061 || response.data.code === 50054) {
			uni.redirectTo({
				url: '/pages/detail/not-view?descript=' + response.data.msg,
			});
			return Promise.reject(response.data);
		}
		if (!response.data.access_token) {
			const code = response.data.code;
			if (code !== 0) {
				uni.showToast({
					title: response.data.msg,
					icon: 'none',
				});
				return Promise.reject(response);
			}
		}

		return response.data;
	},
	(error) => {
		const {
			response,
		} = error;
		// 根据返回的http状态码做不同的处理
		switch (response?.status) {
			case 401:
			case 424:
				uni.$u.throttle(() => {
					// token失效
					uni.navigateTo({
						url: '/pages/login/index',
					});
					storage.clearLoginStorage();
					setTimeout(() => {
						uni.showToast({
							title: response.data.msg,
							icon: 'none',
						});
					});
				}, 1000);
				break;
			case 403:
				// 没有权限
				break;
			case 500:
				// 服务端错误
				break;
			case 503:
				// 服务端错误
				break;
			default:
				break;
		}

		// eslint-disable-next-line
		return Promise.reject(response || {
			message: error.message,
		});
	}
);

export default instance;